<template>
  <div class="useredit">
    <el-scrollbar>
      <!-- height="300px" -->
      <el-form
        ref="userForm"
        class="userForm"
        :model="pageData.formData"
        :rules="pageData.formRules"
        status-icon
        label-width="100px"
      >
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="登录名：" prop="fusername">
              <el-input
                v-model="pageData.formData.fusername"
                placeholder="请输入登录名"
                :disabled="!pageData.isAdd"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="pageData.isAdd">
            <el-form-item label="登录密码：" prop="fpassword">
              <el-input
                show-password
                v-model="pageData.formData.fpassword"
                placeholder="请输入登录密码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="pageData.isAdd">
            <el-form-item label="确认密码：" prop="surepwd">
              <el-input
                show-password
                v-model="pageData.formData.surepwd"
                placeholder="请再次输入登录密码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="用户名称：" prop="ffullname">
              <el-input
                v-model="pageData.formData.ffullname"
                placeholder="请输入用户名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="所属机构：" prop="fgrouporgid">
              <el-input
                v-model="pageData.formData.fgrouporgid"
                placeholder="请输入所属机构"
              ></el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="状态：" prop="state">
              <el-select
                v-model="pageData.formData.state"
                placeholder="请选择状态"
                style="width: 100%"
              >
                <el-option
                  v-for="item in pageData.stateEnumArr.filter(
                    (p) => p.value > -1
                  )"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="绑定职员：" prop="empname">
              <el-input
                v-model="pageData.formData.empname"
                clearable
                readonly
                placeholder="请选择职员"
                @clear="onHandleSelectClear"
                @keydown="onHandleSelectKeydown"
                @dblclick="onHandleSelectOpen"
              >
                <template #suffix>
                  <el-icon style="cursor: pointer" @click="onHandleSelectOpen">
                    <ArrowDown />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-scrollbar>
    <el-row>
      <el-col :span="24" style="text-align: right">
        <el-button @click="onHandleCancel">取 消</el-button>
        <el-button
          v-if="
            (pageData.isAdd && pageData.permissions.Add) ||
            (!pageData.isAdd && pageData.permissions.Edit)
          "
          type="primary"
          @click="onHandleSure"
          >确 定</el-button
        >
      </el-col>
    </el-row>

    <el-dialog
      :width="900"
      title="选择职员"
      v-model="pageData.selectEmpDialogVisible"
      :close-on-click-modal="false"
      append-to-body
      destroy-on-close
      custom-class="editDialog-class"
    >
      <selectemp
        @Ok="onHandleSelectSure"
        @Cancel="() => (pageData.selectEmpDialogVisible = false)"
      />
    </el-dialog>
  </div>
</template>

<script>
import { onMounted, reactive, ref, toRefs } from "vue";
import { ElLoading, ElMessage } from "element-plus";
import utils from "@/common/utils";
import enums from "@/common/enums";
const lodash = require("lodash");

import { createUser, updateUser } from "@/api/system";
import selectemp from "@/components/select/selectemp";
import { ArrowDown } from "@element-plus/icons-vue";

export default {
  name: "UserEdit",
  components: { selectemp, ArrowDown },
  props: {
    modifyObj: { type: Object, required: true },
    currentOrg: { type: Object, required: true },
    isAdd: { type: Boolean, required: true, default: false },
  },
  setup(props, context) {
    onMounted(() => {
      if (props.isAdd) {
        pageState.pageData.formData = {
          fuserid: "",
          fusername: "",
          fpassword: "",
          surepwd: "",
          ffullname: "",
          fpersonid: "",
          empcode: "",
          empname: "",
          fgrouporgid: props.currentOrg.forgid,
          state: enums.StateEnum.Enable.value,
        };
      } else pageState.pageData.formData = lodash.cloneDeep(props.modifyObj);
    });

    const userForm = ref();
    const pageState = reactive({
      pageData: {
        permissions: {
          Add: utils.checkPermission("sysuser_add"),
          Edit: utils.checkPermission("sysuser_edit"),
        },
        stateEnumArr: enums.StateEnum.getObjArray(),
        formData: {},
        formRules: {
          fusername: [
            { required: true, message: "请输入登录名", trigger: "blur" },
          ],
          fpassword: [
            { required: true, message: "请输入登录密码", trigger: "blur" },
          ],
          surepwd: [
            { required: true, message: "请再次输入登录密码", trigger: "blur" },
          ],
          ffullname: [
            { required: true, message: "请输入用户名称", trigger: "blur" },
          ],
          fgrouporgid: [
            { required: true, message: "请选择所属机构", trigger: "blur" },
          ],
          state: [{ required: true, message: "请选择状态", trigger: "blur" }],
        },
        isAdd: props.isAdd,
        selectEmpDialogVisible: false,
      },
    });
    const pageFunc = {
      onHandleSelectClear() {
        pageState.pageData.formData.fpersonid = "";
        pageState.pageData.formData.empcode = "";
        pageState.pageData.formData.empname = "";
      },
      onHandleSelectKeydown(e) {
        e.returnValue = false;
        pageFunc.onHandleSelectOpen();
      },
      onHandleSelectOpen() {
        pageState.pageData.selectEmpDialogVisible = true;
      },
      onHandleSelectSure(selArr) {
        pageState.pageData.formData.ffullname = selArr[0].empname;
        pageState.pageData.formData.fpersonid = selArr[0].empid;
        pageState.pageData.formData.empcode = selArr[0].empcode;
        pageState.pageData.formData.empname = selArr[0].empname;
        pageState.pageData.selectEmpDialogVisible = false;
      },

      onHandleCancel: () => {
        userForm.value?.resetFields();
        context.emit("cancel");
      },
      onHandleSure: () => {
        userForm.value?.validate((valid) => {
          if (valid) {
            const loading = ElLoading.service({
              lock: true,
              background: "rgba(0, 0, 0, 0.7)",
            });
            if (props.isAdd) {
              if (
                pageState.pageData.formData.fpassword !==
                pageState.pageData.formData.surepwd
              ) {
                loading.close();
                ElMessage.error("两次输入密码不一致");
                return;
              }
              createUser(pageState.pageData.formData)
                .then(() => {
                  loading.close();
                  context.emit("ok", {
                    isAdd: props.isAdd,
                    retObj: pageState.pageData.formData,
                  });
                  ElMessage.success("新增成功");
                })
                .catch((error) => {
                  if (error.message === "数据库已存在重复数据") {
                    loading.close();
                    ElMessage.error("登录名重复，请重新输入");
                  } else {
                    loading.close();
                    ElMessage.error(error.message || "请求出错");
                  }
                });
            } else {
              updateUser(pageState.pageData.formData)
                .then(() => {
                  loading.close();
                  context.emit("ok", {
                    isAdd: props.isAdd,
                    retObj: pageState.pageData.formData,
                  });
                  ElMessage.success("修改成功");
                })
                .catch((error) => {
                  loading.close();
                  ElMessage.error(error.message || "请求出错");
                });
            }
          } else return false;
        });
      },
    };

    return {
      userForm,
      ...toRefs(pageState),
      ...pageFunc,
    };
  },
};
</script>

<style lang="scss">
.useredit {
  height: 100%;
  background-color: white;
  .userForm {
    width: calc(100% - 6px);
  }
}
</style>
